package cn.itcast.Dao.impl;

import cn.itcast.Dao.UserDao;
import cn.itcast.domain.Role;
import cn.itcast.domain.User;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.List;

/**
 * @author wgq
 * @date 2019-09-20 18:38
 */
@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public User findByUsernameAndPassWord(String username, String password) {
        User user = jdbcTemplate.queryForObject("select * from sys_user where username = ? and password = ?",
                new BeanPropertyRowMapper<User>(User.class), username, password);
        return user;
    }

    @Override
    public List<User> findAll() {
        List<User> userList = jdbcTemplate.query("select * from sys_user", new BeanPropertyRowMapper<User>(User.class));
        return userList;
    }

    @Override
    public Long save(final User user) {
        jdbcTemplate.update("insert into sys_user values(?,?,?,?,?)",null,user.getUsername(),
                user.getEmail(),user.getPassword(),user.getPhoneNum());
        Long userId = jdbcTemplate.queryForObject("select LAST_INSERT_ID()",Long.class);
        return userId;
    }

    @Override
    public void saveUserRoleRel(Long id, Long[] roleIds) {
        for (Long roleId : roleIds) {
            jdbcTemplate.update("insert into sys_user_role values(?,?)",id,roleId);
        }
    }

    @Override
    public void delUserRoleRel(Long userId) {
        jdbcTemplate.update("delete from sys_user_role where userId = ?",userId);
    }

    @Override
    public void delUser(Long userId) {
        jdbcTemplate.update("delete from sys_user where id = ?",userId);
    }

    @Override
    public User findById(Long userId) {
        User user = jdbcTemplate.queryForObject("select * from sys_user where id = ?", new BeanPropertyRowMapper<User>(User.class), userId);
        return user;
    }

    @Override
    public void updateUser(User user) {
        jdbcTemplate.update("update sys_user set username = ?, email= ?, phoneNum=? where id = ?",user.getUsername(),user.getEmail(),user.getPhoneNum(),user.getId());
    }
}
